#!/bin/bash

# SSL证书定时任务检查和维护脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_title() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "    SSL证书定时任务检查工具"
    echo "=================================================="
    echo -e "${NC}"
}

# 检查cron服务状态
check_cron_service() {
    log_info "检查cron服务状态..."
    
    if systemctl is-active --quiet cron; then
        log_info "✓ cron服务正在运行"
    else
        log_error "✗ cron服务未运行"
        echo "启动cron服务: sudo systemctl start cron"
        echo "设置开机自启: sudo systemctl enable cron"
        return 1
    fi
}

# 检查定时任务配置
check_crontab() {
    log_info "检查SSL证书续期定时任务..."
    
    # 获取当前项目路径
    CURRENT_DIR=$(pwd)
    EXPECTED_CRON="0 2 * * * $CURRENT_DIR/renew-ssl.sh >> /var/log/ssl-renewal.log 2>&1"
    
    # 检查是否存在SSL续期任务
    if sudo crontab -l 2>/dev/null | grep -q "renew-ssl.sh"; then
        log_info "✓ 找到SSL证书续期定时任务"
        
        # 显示当前的定时任务
        echo "当前的SSL续期定时任务:"
        sudo crontab -l 2>/dev/null | grep "renew-ssl.sh"
        
        # 检查路径是否正确
        CURRENT_CRON=$(sudo crontab -l 2>/dev/null | grep "renew-ssl.sh")
        if echo "$CURRENT_CRON" | grep -q "$CURRENT_DIR"; then
            log_info "✓ 定时任务路径正确"
        else
            log_warn "⚠ 定时任务路径可能不正确"
            echo "当前任务: $CURRENT_CRON"
            echo "期望任务: $EXPECTED_CRON"
            return 2
        fi
    else
        log_error "✗ 未找到SSL证书续期定时任务"
        echo "期望的定时任务: $EXPECTED_CRON"
        return 1
    fi
}

# 检查续期脚本
check_renewal_script() {
    log_info "检查续期脚本..."
    
    if [ -f "./renew-ssl.sh" ]; then
        log_info "✓ 续期脚本存在"
        
        # 检查执行权限
        if [ -x "./renew-ssl.sh" ]; then
            log_info "✓ 续期脚本有执行权限"
        else
            log_warn "⚠ 续期脚本没有执行权限"
            echo "修复命令: chmod +x ./renew-ssl.sh"
        fi
        
        # 检查脚本配置
        if grep -q "PROJECT_DIR=\"$(pwd)\"" ./renew-ssl.sh; then
            log_info "✓ 续期脚本路径配置正确"
        else
            log_warn "⚠ 续期脚本路径配置可能不正确"
        fi
    else
        log_error "✗ 续期脚本不存在"
        return 1
    fi
}

# 检查日志文件
check_logs() {
    log_info "检查SSL续期日志..."
    
    if [ -f "/var/log/ssl-renewal.log" ]; then
        log_info "✓ 续期日志文件存在"
        
        # 显示最近的日志
        echo "最近的续期日志:"
        sudo tail -10 /var/log/ssl-renewal.log 2>/dev/null || echo "日志文件为空"
    else
        log_warn "⚠ 续期日志文件不存在（首次运行后会创建）"
    fi
    
    # 检查系统cron日志
    if [ -f "/var/log/cron.log" ]; then
        log_info "检查系统cron日志中的SSL任务..."
        if sudo grep -q "renew-ssl.sh" /var/log/cron.log 2>/dev/null; then
            echo "最近的cron执行记录:"
            sudo grep "renew-ssl.sh" /var/log/cron.log | tail -5
        else
            log_warn "⚠ 在cron日志中未找到SSL续期任务执行记录"
        fi
    fi
}

# 测试续期脚本
test_renewal_script() {
    log_info "测试续期脚本（干运行）..."
    
    if [ -f "./renew-ssl.sh" ]; then
        echo "脚本内容检查:"
        echo "- 项目路径: $(grep "PROJECT_DIR=" ./renew-ssl.sh)"
        echo "- 域名配置: $(grep "DOMAIN=" ./renew-ssl.sh)"
        
        echo
        echo "是否要手动运行续期脚本进行测试? (y/N): "
        read -r test_run
        if [ "$test_run" = "y" ] || [ "$test_run" = "Y" ]; then
            log_info "运行续期脚本..."
            sudo ./renew-ssl.sh
        fi
    else
        log_error "续期脚本不存在，无法测试"
    fi
}

# 修复定时任务
fix_crontab() {
    log_info "修复SSL证书续期定时任务..."
    
    CURRENT_DIR=$(pwd)
    NEW_CRON="0 2 * * * $CURRENT_DIR/renew-ssl.sh >> /var/log/ssl-renewal.log 2>&1"
    
    # 删除旧的SSL续期任务
    sudo crontab -l 2>/dev/null | grep -v "renew-ssl.sh" | sudo crontab - 2>/dev/null || true
    
    # 添加新的任务
    (sudo crontab -l 2>/dev/null; echo "$NEW_CRON") | sudo crontab -
    
    log_info "✓ 定时任务已更新"
    echo "新的定时任务: $NEW_CRON"
}

# 显示维护建议
show_maintenance_tips() {
    echo
    echo -e "${BLUE}📋 SSL证书定时任务维护建议:${NC}"
    echo
    echo "1. 定期检查 (建议每月一次):"
    echo "   sudo ./check-ssl-cron.sh"
    echo
    echo "2. 查看续期日志:"
    echo "   sudo tail -f /var/log/ssl-renewal.log"
    echo
    echo "3. 手动测试续期:"
    echo "   sudo ./renew-ssl.sh"
    echo
    echo "4. 查看证书过期时间:"
    echo "   sudo openssl x509 -in /etc/letsencrypt/live/pecco.pet/fullchain.pem -enddate -noout"
    echo
    echo "5. 重新部署后检查:"
    echo "   - 定时任务路径是否正确"
    echo "   - 续期脚本是否存在且可执行"
    echo
    echo "6. 证书续期时间:"
    echo "   - Let's Encrypt证书有效期90天"
    echo "   - 脚本会在过期前30天自动续期"
    echo "   - 定时任务每天凌晨2点检查"
}

# 主函数
main() {
    print_title
    
    local has_issues=0
    
    # 执行各项检查
    check_cron_service || has_issues=1
    echo
    
    check_crontab
    local crontab_status=$?
    if [ $crontab_status -ne 0 ]; then
        has_issues=1
    fi
    echo
    
    check_renewal_script || has_issues=1
    echo
    
    check_logs
    echo
    
    # 如果有问题，提供修复选项
    if [ $has_issues -ne 0 ]; then
        echo -e "${YELLOW}发现一些问题，是否要修复? (y/N): ${NC}"
        read -r fix_choice
        if [ "$fix_choice" = "y" ] || [ "$fix_choice" = "Y" ]; then
            if [ $crontab_status -ne 0 ]; then
                fix_crontab
            fi
            
            # 修复脚本权限
            if [ -f "./renew-ssl.sh" ] && [ ! -x "./renew-ssl.sh" ]; then
                chmod +x ./renew-ssl.sh
                log_info "✓ 已修复续期脚本执行权限"
            fi
        fi
    else
        log_info "✅ 所有检查都通过，SSL证书定时任务配置正常！"
    fi
    
    # 询问是否测试
    echo
    echo "是否要测试续期脚本? (y/N): "
    read -r test_choice
    if [ "$test_choice" = "y" ] || [ "$test_choice" = "Y" ]; then
        test_renewal_script
    fi
    
    show_maintenance_tips
}

# 运行主函数
main "$@"
